import {createSlice, PayloadAction} from "@reduxjs/toolkit";
import {settingSlice} from "@/store/modules/settingSlice.ts";
import {theme} from "antd";

interface InitialStateType {
    themeLayout: 'BlogLayout' | 'ClassicsLayout',
    darkMode: boolean;
    settings: any;  //App.Theme.ThemeSetting;
}

const themeSchemes: UnionKey.ThemeScheme[] = ['light', 'dark', 'auto'];


/**
 * 初始化主题设置
 *
 */
const initThemeSettings = (): any => {

    return {
        themeScheme: 'light',
    }
}


const initialState: InitialStateType = {
    themeLayout: 'ClassicsLayout',
    darkMode: false,
    settings: initThemeSettings()
};

export const DARK_MODE_MEDIA_QUERY = '(prefers-color-scheme: dark)';

export function updateDarkMode(themeScheme: UnionKey.ThemeScheme) {
    if (themeScheme === 'dark') {
        return true;
    } else if (themeScheme === 'light') {
        return false;
    }
    return window.matchMedia(DARK_MODE_MEDIA_QUERY).matches;
}


export const themeSlice = createSlice({
    name: 'theme',
    initialState,
    reducers: {
        setDarkMode(state, { payload }: PayloadAction<boolean>) {
            state.darkMode = payload;
        },
        setThemeScheme(state, { payload }: PayloadAction<UnionKey.ThemeScheme>) {
            state.darkMode = updateDarkMode(payload);
            state.settings.themeScheme = payload;
        },
        setThemeLayout(state, { payload }: PayloadAction<'BlogLayout' | 'ClassicsLayout'>){
            state.themeLayout = payload;
        }
    },
    selectors: {
        getThemeLayout: theme => theme.themeLayout,
        getThemeSettings: theme => theme.settings,
        getDarkMode: theme => theme.darkMode
    }
})

export const {
    // actions
    setDarkMode,
    setThemeScheme,
    setThemeLayout
} = themeSlice.actions;


export const {
    getDarkMode,
    getThemeLayout,
    getThemeSettings
} = themeSlice.selectors;



export default themeSlice.reducer;
